extends Camera2D

@export var fixed_point:Node2D

@export var follow_target:Node2D
@export var speed_factor:float = 3
var cam_actual_pos:Vector2

@export var cam_limit:Node2D
signal set_cam_offset


func _ready() -> void:
	set_cam_limit()
	
	await get_tree().process_frame
	follow_immediate()
		

func follow_immediate():
	if follow_target:
		cam_actual_pos = follow_target.global_position
		
	
func set_cam_limit():
	if not cam_limit or cam_limit.get_child_count() <= 0: return
	
	var left = cam_limit.find_child("Left") as Marker2D
	var top = cam_limit.find_child("Top") as Marker2D
	var right = cam_limit.find_child("Right") as Marker2D
	var bottom = cam_limit.find_child("Bottom") as Marker2D
	
	limit_left = left.global_position.x
	limit_top = top.global_position.y
	limit_right = right.global_position.x
	limit_bottom = bottom.global_position.y


func _physics_process(delta: float) -> void:
	if fixed_point:
		cam_actual_pos = fixed_point.global_position
		return
	
	if not follow_target: return
	
	cam_actual_pos = cam_actual_pos.lerp(follow_target.global_position, speed_factor * delta)  
	
	var cam_offset = cam_actual_pos.round() - cam_actual_pos
	
	set_cam_offset.emit(cam_offset)
	
	global_position = cam_actual_pos.round()

	
	
	
